package com.kancy.vip.util;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ThreadExecutorUtil {
    public static void execute(ThreadHandler threadHandler){
        execute(threadHandler, 1, 0);
    }
    public static void execute(ThreadHandler threadHandler, int threadSize){
        execute(threadHandler, threadSize, threadSize);
    }
    public static void execute(ThreadHandler threadHandler, int threadSize, int countDownLatchSize){
        assert countDownLatchSize <= threadSize : "countDownLatchSize 必须小于 threadSize ";
        CountDownLatch countDownLatch = new CountDownLatch(countDownLatchSize);
        List<Thread> threadList = new ArrayList();
        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread(() -> {
                try {
                    // 等待其他线程
                    countDownLatch.await();
                    threadHandler.handler(new ThreadWapper(Thread.currentThread()));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            threadList.add(thread);
            thread.start();
            countDownLatch.countDown();
        }
        threadList.stream().forEach((t)->{
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        threadList.clear();
        threadList = null; // help gc
    }

    public interface ThreadHandler{
        void handler(ThreadWapper thread);
    }
    public static class ThreadWapper{
        private Thread thread;
        public ThreadWapper(Thread thread) {
            this.thread = thread;
        }
        public void print(){
            print(thread);
        }
        public void print(Object obj){
            System.out.println(thread.getName() + "-" + System.currentTimeMillis() + "-" + obj);
        }
    }
}
